<template>
	<diyNavVue :title="toInfo.name"></diyNavVue>
	<view class="message-list">
		<view :class="['message-item', item.fromId===meId?'right': '']" v-for="(item,index) in messageList"
			:key="index">
			<image v-if="item.fromId !== meId" class="message-avatar" :src="toInfo.avatar" mode=""></image>
			<rich-text v-if="typeof(item.message)==='string'" :nodes="item.message"></rich-text>
			<template v-else>
				<up-icon name="mic" @click="startPlayAudio(item.message)"></up-icon>
			</template>
			<image v-if="item.fromId === meId" class="message-avatar" :src="myInfo.avatar" mode=""></image>
		</view>
	</view>
	<view class="input-model">
		<view class="input-con">
			<up-icon name="volume-fill" @longpress="startScorder" @touchend="stopScorder"></up-icon>
			<up-input v-model="messageValue" placeholder="请输入内容" border="surround" clearable></up-input>
			<button size="mini" type="primary" @click="doSend">发送</button>
			<up-icon name="star-fill" color="#2979ff" size="28" @click="handleIcon"></up-icon>
			<up-icon name="photo-fill" color="#2979ff" size="28" @click="selectImage"></up-icon>
		</view>
		<view v-if="showIcon" class="icon-list">
			<image @click="selectedIcon(item)" class="icon-image" v-for="item in iconList" :src="item.url" mode=""></image>
		</view>
	</view>
</template>

<script setup>
	import diyNavVue from '../../components/diy-nav/diy-nav.vue';
	import io from '@hyoga/uni-socket.io';
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		ref
	} from 'vue';
	// 构造audio上下文对象
	const innerAudioContext = uni.createInnerAudioContext()
	// #ifdef MP-WEIXIN
	// 生成一个全局的录音管理器,uni.getRecorderManager方法H5不支持
	const recorderManager = uni.getRecorderManager()
	// 使用录音管理器监听录音停止的事件
	recorderManager.onStop((res) => {
		console.log(res)
		// 停止录音之后咱们上传录音文件
		setTimeout(() => {
			const url = 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3';
			const messageObj = {
				fromId: meId.value,
				toId: toId.value,
				message: {
					type: 'audio',
					url
				}
			}
			messageList.value.push(messageObj)
			socket.emit('sendMsg', messageObj)
		}, 2000)
	})
	// #endif
	const showIcon = ref(false)
	const handleIcon = () => {
		showIcon.value = !showIcon.value
	}
	const selectedIcon = (item) => {
		console.log(item)
		messageValue.value += item.code
	}
	const iconList = ref([
		{url: '/static/icon/bs.png', code: '/bs'},
		{url: '/static/icon/cj.png', code: '/cj'},
		{url: '/static/icon/eye.png', code: '/eye'},
		{url: '/static/icon/yg.png', code: '/yg'},
		{url: '/static/icon/sq.png', code: '/sq'}
	])
	// 长按开始录音
	const startScorder = () => {
		console.log('开始录音')
		recorderManager.start()
	}
	// 移开手指停止录音
	const stopScorder = () => {
		console.log('停止录音')
		recorderManager.stop()
	}
	// 点击播放音频
	const startPlayAudio = (audioObj) => {
		innerAudioContext.src =  audioObj.url
		if(innerAudioContext.paused) {
			innerAudioContext.play()
		} else {
			innerAudioContext.pause()
		}
	}
	const selectImage = () => {
		// 选择图片的api
		uni.chooseImage({
			success(res) {
				// 选择好了，应该把这张图片上传
				// 上传成功之后，咱们能拿到上传之后的图片的url
				// console.log(res);
				setTimeout(() => {
					// 模拟2秒钟图片上传成功
					// 模拟图片上传成功之后返回的url
					const url = 'https://gips2.baidu.com/it/u=1651586290,17201034&fm=3028&app=3028&f=JPEG&fmt=auto&q=100&size=f600_800'
					const messageObj = {
						fromId: meId.value,
						toId: toId.value,
						message: `<img style="width: 100px;" src="${url}">`
					}
					// 添加到消息列表
					messageList.value.push(messageObj)
					// 发送消息
					socket.emit('sendMsg', messageObj)
				}, 2000)
			}
		})
	}
	
	const messageValue = ref('')
	// 静态模拟所有用户的信息
	const personList = [{
		id: 'bin',
		name: '李少斌',
		avatar: 'http://gips3.baidu.com/it/u=100751361,1567855012&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280'
	}, {
		id: 'zxy',
		name: '张学友',
		avatar: 'http://gips2.baidu.com/it/u=195724436,3554684702&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960'
	}, {
		id: 'ldh',
		name: '刘德华',
		avatar: 'http://gips2.baidu.com/it/u=195724436,3554684702&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960'
	}]
	let socket = null
	const linkSocket = () => {
		console.log(meId.value)
		socket = io('ws://localhost:3000', {
			path: '/socket',
			query: {
				id: meId.value
			},
			reconnection: false,
			transports: ['websocket', 'polling'],
			timeout: 5000,
		});
		socket.on('connect', () => {
			console.log('我(客户端)链接服务端成功了')
			doHeart()
			// 注册一个事件
			socket.on('reciveMsg', (info) => {
				console.log('服务端给我发消息了', info)
				messageList.value.push(info)
			})
			socket.on('pang', () => {
				console.log('一次心跳检测完成')
			})
		})
		socket.on('connect_error', () => {
			console.log('链接错误')
			timer && clearInterval(timer)
			linkSocket()
		})
		socket.on('disconnect', () => {
			console.log('链接突然挂掉了')
			timer && clearInterval(timer)
			linkSocket()
		})
	}
	let timer = null
	const doHeart = () => {
		console.log('xintiaojiance')
		timer && clearInterval(timer)
		timer = setInterval(() => {
			socket.emit('ping')
		}, 10000)
	}
	const meId = ref('')
	const toId = ref('')
	const messageList = ref([
		// {
		// 	fromId: 'zxy',
		// 	message: '您好',
		// 	toId: 'bin'
		// },
		// {	fromId: 'zxy',
		// 	message: '房子是中建置地开发，精装修',
		// 	toId: 'bin'
		// },
		// {
		// 	fromId: 'bin',
		// 	message:'你好，请问房子还在吗',
		// 	toId: 'zxy'
		// }
	])
	const myInfo = ref({})
	const toInfo = ref({})
	// 获取用户信息
	const getUserInfo = () => {
		myInfo.value = personList.find(item => item.id === meId.value) || {}
		toInfo.value = personList.find(item => item.id === toId.value) || {}
	}

	onLoad((options) => {
		toId.value = options.toId
		meId.value = options.meId
		// 进入到页面，聊天双方的用户id已经确认了
		// 通过用户id调用接口来获取用户信息
		getUserInfo()
		linkSocket()
	})
	onUnload(() => {
		timer && clearInterval(timer)
	})
	const codeToImg = (str) => {
		// <img src="/static/icon/bs/png">/yg/sq<img src="/static/icon/bs/png">
		let newStr = str
		iconList.value.forEach(item => {
			// {code: '/bs', url: '/static/icon/bs/png'}
			newStr = newStr.replaceAll(item.code, `<img style="width: 60px;height: 60px;" src="${item.url}">`)
		})
		console.log(newStr)
		return newStr
		
	}
	const doSend = () => {
		console.log(messageValue.value)
		console.log(meId.value)
		const messageObj = {
			fromId: meId.value,
			// 表情: 发送之前把表情标识替换成对应的图片标签
			message: codeToImg(messageValue.value),
			toId: toId.value
		}
		messageList.value.push(messageObj)
		// 触发服务端注册的事件
		socket.emit('sendMsg', messageObj)
		messageValue.value = ''
	}
</script>

<style lang="scss" scoped>
	.message-item {
		display: flex;

		.message-avatar {
			width: 60rpx;
			height: 60rpx;
		}

		&.right {
			justify-content: flex-end;
		}
	}

	.input-model {
		position: fixed;
		width: 100vw;
		bottom: 0;

		.input-con {
			display: flex;
			align-items: center;
		}
	}
	.icon-list{
		.icon-image{
			width: 30rpx;
			height: 30rpx;
		}
	}
</style>